//删除
$("#removeBtn").click(function () {
    confirmAlert(function () {
        var ids = getSelectIds();
        ajaxJson("/admin/classify/ajax/delete", {"ids": ids.toString()}, function (res) {
            if (res.status) {
                refreshZtree();
                $("#removeBtn").prop('disabled', true);
                $("#updateBtn").prop('disabled', true);
            }
        })
    })
})
//修改
$("#updateBtn").click(function () {
    var ids = getSelectIds();
    if (ids) {
        location.href = "/admin/classify/save?id=" + ids[0]
    }
})
//获取选中id
function getSelectIds(){
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getCheckedNodes(true);
    var selections = []
    for(var i = 0;i<nodes.length;i++){
        selections.push(nodes[i].id);
    }
    return selections;
}

var setting = {
    /*async: {
        enable: true,
        url:"/admin/classify/ajax/child",
        autoParam:["id"],
        dataFilter: filter
    },*/
    check: {
        enable: true,
        chkboxType: { "Y": "s", "N": "ps" }
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: "00000000"
        }
    },
    callback: {
        onCheck: zTreeOnCheck
    }
};

//勾选事件
function zTreeOnCheck(event, treeId, treeNode) {
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
    var nodes = treeObj.getCheckedNodes(true);
    if(nodes.length>0){
        $("#removeBtn").prop('disabled', false);
        $("#updateBtn").prop('disabled', false);
    }else{
        $("#removeBtn").prop('disabled', true);
        $("#updateBtn").prop('disabled', true);
    }
};

function filter(treeId, parentNode, res) {
    if(res.status){
        return res.data;
    }
    return null;
}

$(document).ready(function () {
    // $.fn.zTree.init($("#treeDemo"), setting);
    loadZtree();
});

//刷新分类树
function refreshZtree(){
    $.fn.zTree.destroy("treeDemo");
    loadZtree();
}

//加载分类树
function loadZtree(){
    ajaxJson("/admin/classify/ajax/all",{},function(res){
        if(res.status){
            $.fn.zTree.init($("#treeDemo"), setting, res.data);
        }
    })
}